package com.ocom.nettyxf.service.impl;

import cn.hutool.core.util.HexUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ocom.common.entity.card.EntityCardInfo;
import com.ocom.common.request.payhandle.*;
import com.ocom.common.resp.RespMachMessage;
import com.ocom.common.resp.Result;
import com.ocom.common.utils.DateUtils;
import com.ocom.common.utils.NumConvertUtil;
import com.ocom.common.utils.RandomUtil;
import com.ocom.nettyxf.client.PayHandleFeignService;
import com.ocom.nettyxf.client.XfRecodeClientService;
import com.ocom.nettyxf.ropo.TcpServiceRopo;
import com.ocom.nettyxf.service.PayService;
import com.ocom.nettyxf.vo.*;
import com.ocom.redis.util.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @Description: TODO
 * @Author: 朱晖
 * @Date: 2022/10/21
 **/

@Slf4j
@Service
@Resource
public class PayServerImpl implements PayService {


	@Resource
	private RedisUtil redisUtil;

	@Autowired
	private PayHandleFeignService payHandleFeignService;

	@Autowired
	private XfRecodeClientService xfRecodeClientService;

	@Override
	public byte[] pay(TcpServiceRopo tcpServiceRopo) throws Exception {

//		return new byte[0];
//		Thread.sleep(4000);

		//要返回的对象
		TcpServiceRopo resp = new TcpServiceRopo();
		//赋返回值  全是16进制字符串
		resp.setMachId(tcpServiceRopo.getMachId());
		resp.setEdition(tcpServiceRopo.getEdition());
		resp.setType(tcpServiceRopo.getType());
		resp.setPackageNum(tcpServiceRopo.getPackageNum());
		resp.setCommandType(tcpServiceRopo.getCommandType());

		PayVo payVo = new PayVo();

		//类型，1-刷卡，4-刷脸，5-付款码，7-ocom离线码
		String payType = tcpServiceRopo.getCommandParam().substring(0, 2);
		Integer payTypeInt = NumConvertUtil.HexStringToInt(payType);
		//操作类型，0x01金额消费；0x02计次消费；0x03金额充值；0x04次数充值；0x05订餐，0x06菜单消费；其他预留
		String handleType = tcpServiceRopo.getCommandParam().substring(2, 4);
		//1-食堂；2-小卖部
		String comsumeType = tcpServiceRopo.getCommandParam().substring(4, 6);
		//人员pid	4	HEX	前高后低，类型为4、7时有效  前高后低，类型为1时卡号，4或7时为人员pid
//		String pId = tcpServiceRopo.getCommandParam().substring(6, 14);
//		Integer pIdInt = NumConvertUtil.HexStringToInt(pId);
		//设备交易号 13	HEX，4字节位设备号+ 7字节交易时间yyyyMMddHHmmssxxxx+2字节随机数
		String orderNo = tcpServiceRopo.getCommandParam().substring(6, 32);
		//消费金额	4	HEX	前高后低
		String money = tcpServiceRopo.getCommandParam().substring(32, 40);
		Integer moneyInt = NumConvertUtil.HexStringToInt(money);
		//内容长度
		String len = tcpServiceRopo.getCommandParam().substring(40, 44);
		Integer lenInt = NumConvertUtil.HexStringToInt(len);
		//内容
		String content = tcpServiceRopo.getCommandParam().substring(44, 44 + lenInt*2);

		Long companyId = ((Integer) redisUtil.hmGet("tcpXfMach:" + tcpServiceRopo.getMachId(), "companyId")).longValue();

		Result result = null;

		if (payTypeInt == 1) {
			QrCardPayRequest request = new QrCardPayRequest();
			request.setCompanyId(companyId);
			request.setMachNo(tcpServiceRopo.getMachId());
			request.setTradeNo(orderNo);
			request.setAmount(moneyInt);
			request.setType(1);
			request.setAuthCode(content);
			request.setConsType(NumConvertUtil.HexStringToInt(comsumeType));

			result = payHandleFeignService.getPayCard(request);

			if (result.getCode() != 200) {
				log.info("Tcp_pay-返回失败 11【{}】【{}】 【{}】",orderNo, tcpServiceRopo, result);
				resp.setCommandParam(result.getCode().toString(),4,result.getMsg());
				String rc = resp.getHexStr();
				return HexUtil.decodeHex(rc);
			}
		}


		if (payTypeInt == 5) {
			String codeStr = NumConvertUtil.hexStringToString(content);
			if(codeStr.startsWith("CT")){
				QrCardPayRequest request = new QrCardPayRequest();
				request.setCompanyId(companyId);
				request.setMachNo(tcpServiceRopo.getMachId());
				request.setTradeNo(orderNo);
				request.setAmount(moneyInt);
				request.setType(21);
				request.setAuthCode(codeStr);
				request.setConsType(NumConvertUtil.HexStringToInt(comsumeType));

				result = payHandleFeignService.getPayCard(request);

				if (result.getCode() != 200) {
					log.info("Tcp_pay-返回失败 110【{}】【{}】 【{}】",orderNo, tcpServiceRopo, result);
					resp.setCommandParam(result.getCode().toString(),4,result.getMsg());
					String rc = resp.getHexStr();
					return HexUtil.decodeHex(rc);
				}
			}else{
				QrCodePayRequest request = new QrCodePayRequest();
				request.setCompanyId(companyId);
				request.setMachNo(tcpServiceRopo.getMachId());
				request.setTradeNo(orderNo);
				request.setAmount(moneyInt);
				request.setAuthCode(NumConvertUtil.hexStringToString(content));
				request.setConsType(NumConvertUtil.HexStringToInt(comsumeType));
				result = payHandleFeignService.qrCodePay(request);
				if (result.getCode() != 200) {
					if(result.getCode()==3030){
						log.info("Tcp_pay-返回失败 44【{}】【{}】 【{}】",orderNo, tcpServiceRopo, result);
						result.setCode(3030);
						resp.setCommandParam("3030",4,result.getMsg());
						String rc = resp.getHexStr();
						return HexUtil.decodeHex(rc);
					}else{
						log.info("Tcp_pay-返回支付中 55【{}】【{}】 【{}】",orderNo, tcpServiceRopo, result);
						result.setCode(802);
						resp.setCommandParam("0802",4,result.getMsg());
						String rc = resp.getHexStr();
						return HexUtil.decodeHex(rc);
					}
				}
			}
		}

		if (payTypeInt == 7) {

			Integer pIdInt = NumConvertUtil.HexStringToInt(content);

			QrCardPayRequest request = new QrCardPayRequest();
			request.setCompanyId(companyId);
			request.setMachNo(tcpServiceRopo.getMachId());
			request.setTradeNo(orderNo);
			request.setAmount(moneyInt);
			request.setType(7);
			request.setAuthCode(pIdInt.toString());
			request.setConsType(NumConvertUtil.HexStringToInt(comsumeType));

			result = payHandleFeignService.getPayCard(request);
			if (result.getCode() != 200) {
				log.info("Tcp_pay-返回失败 77【{}】【{}】 【{}】",orderNo, tcpServiceRopo, result);
				resp.setCommandParam(result.getCode().toString(),4,result.getMsg());
				String rc = resp.getHexStr();
				return HexUtil.decodeHex(rc);
			}
		}

		if (result == null) {
			log.info("Tcp_pay-返回失败 88【{}】 【{}】", tcpServiceRopo, result);
			resp.setCommandParam("0501",4,"底层无返回异常");
			String rc = resp.getHexStr();
			return HexUtil.decodeHex(rc);
		}


		JSONObject jsonObject = JSON.parseObject(JSON.toJSONString(result.getData()));

		payVo.setDiscount(NumConvertUtil.IntToHexStringNum(Math.abs(jsonObject.getInteger("discount")), 4));
		payVo.setRealMoney(NumConvertUtil.IntToHexStringNum(Math.abs(jsonObject.getInteger("payAmount")), 8));
		payVo.setType(payType);


		JSONObject jsonObject1 = JSON.parseObject(JSON.toJSONString(jsonObject.get("accountInf")));

		if (jsonObject1 != null) {
			if (jsonObject1.getString("name") != null) {
				String name = NumConvertUtil.toGBK(jsonObject1.getString("name"));
				if (name.length() < 40) {
					int len1 = name.length();
					for (int i = len1; i < 40; i++) {
						name = name + "0";
					}
				}
				if (name.length() > 40) {
					name=name.substring(0,40);
				}
				payVo.setName(name);
			}
			if (jsonObject1.getString("expireDate") != null) {
				Date date = DateUtils.strToDate(jsonObject1.getString("expireDate"));
				payVo.setCardValid(DateUtils.getStrDate(date, "yyyyMMddHHmmss"));
			}

			if (jsonObject1.getInteger("money") != null) {
				payVo.setBalance(NumConvertUtil.IntToHexStringNum(jsonObject1.getInteger("money"), 8));
			}
			if (jsonObject1.getInteger("allowance") != null) {
				payVo.setSubBalance(NumConvertUtil.IntToHexStringNum(jsonObject1.getInteger("allowance"), 8));
			}
			if (jsonObject1.getInteger("cardtype") != null) {
				payVo.setCardType(NumConvertUtil.IntToHexStringNum(jsonObject1.getInteger("cardtype"), 2));
			}
		}

		resp.setCommandParam(payVo.getHexStr());
		String rc = resp.getHexStr();

		log.info("Tcp_pay-返回【{}】 【{}】", tcpServiceRopo, payVo);



		return HexUtil.decodeHex(rc);

	}


	@Override
	public byte[] refund(TcpServiceRopo tcpServiceRopo) throws Exception {
		//要返回的对象
		TcpServiceRopo resp = new TcpServiceRopo();
		//赋返回值  全是16进制字符串
		resp.setMachId(tcpServiceRopo.getMachId());
		resp.setEdition(tcpServiceRopo.getEdition());
		resp.setType(tcpServiceRopo.getType());
		resp.setPackageNum(tcpServiceRopo.getPackageNum());
		resp.setCommandType(tcpServiceRopo.getCommandType());

		RefundVo refundVo = new RefundVo();

		Long companyId = ((Integer) redisUtil.hmGet("tcpXfMach:" + tcpServiceRopo.getMachId(), "companyId")).longValue();

		String money = tcpServiceRopo.getCommandParam().substring(0,8);
		Integer moneyInt = NumConvertUtil.HexStringToInt(money);

		String len =  tcpServiceRopo.getCommandParam().substring(8,10);
		Integer lenInt = NumConvertUtil.HexStringToInt(len);

		String orderNo = tcpServiceRopo.getCommandParam().substring(10, 10+lenInt*2);
		orderNo = NumConvertUtil.hexStringToString(orderNo);

		QrCodeRefundRequest request = new QrCodeRefundRequest();
		request.setCompanyId(companyId);
		request.setMachNo(tcpServiceRopo.getMachId());
		request.setRefundAmount(moneyInt);
		request.setOrigTradeNo(orderNo);
		request.setTradeNo(DateUtils.getStrDate(new Date(), "yyyyMMddHHmmss")+ RandomUtil.generateNumber(12));

		Result result = payHandleFeignService.qrCodeRefund(request);

		log.info("Tcp_refund-返回【{}】 【{}】", request, result);


		if (result.getCode() != 200) {
			resp.setCommandParam(result.getCode().toString(),4,result.getMsg());
			String rc = resp.getHexStr();
			return HexUtil.decodeHex(rc);
		}

		JSONObject jsonObject = JSON.parseObject(JSON.toJSONString(result.getData()));

		refundVo.setMoney(NumConvertUtil.IntToHexStringNum(jsonObject.getInteger("refundAmount"), 8));

		resp.setCommandParam(refundVo.getHexStr());
		String rc = resp.getHexStr();
		return HexUtil.decodeHex(rc);
	}


	@Override
	public byte[] recodeUpload(TcpServiceRopo tcpServiceRopo) throws Exception {
		//要返回的对象
		TcpServiceRopo resp = new TcpServiceRopo();
		//赋返回值  全是16进制字符串
		resp.setMachId(tcpServiceRopo.getMachId());
		resp.setEdition(tcpServiceRopo.getEdition());
		resp.setType(tcpServiceRopo.getType());
		resp.setPackageNum(tcpServiceRopo.getPackageNum());
		resp.setCommandType(tcpServiceRopo.getCommandType());

		RecodeUploadVo recodeUploadVo = new RecodeUploadVo();

		Long companyId = ((Integer) redisUtil.hmGet("tcpXfMach:" + tcpServiceRopo.getMachId(), "companyId")).longValue();

		//类型，1-刷卡，4-刷脸，5-付款码，7-ocom离线码
		String payType = tcpServiceRopo.getCommandParam().substring(0, 2);
		Integer payTypeInt = NumConvertUtil.HexStringToInt(payType);

		if(payTypeInt>7){
			//记录号	4	HEX	前高后低
			log.error("异常订单上传【{}】【{}】【{}】",tcpServiceRopo.getMachId(),payTypeInt,tcpServiceRopo);
			String recode = tcpServiceRopo.getCommandParam().substring(14, 22);
			resp.setCommandParam("0000"+recode);
			log.info("异常记录 S7fLynTp 设备号 【{}】 请求内容 【{}】 请求实体 【{}】",tcpServiceRopo.getMachId(),tcpServiceRopo.getCommandParam(),tcpServiceRopo);
			String rc = resp.getHexStr();
			return HexUtil.decodeHex(rc);
		}

		if (payTypeInt != 3 && payTypeInt != 1 && payTypeInt != 4 && payTypeInt != 5 && payTypeInt != 7) {
			resp.setCommandParam("0000",4,"支付类型不支持");
			String rc = resp.getHexStr();
			log.info("异常记录 z9AnTWmN 设备号 【{}】 请求内容 【{}】 请求实体 【{}】",tcpServiceRopo.getMachId(),tcpServiceRopo.getCommandParam(),tcpServiceRopo);
			return HexUtil.decodeHex(rc);
		}

		//人员pid/卡号	4	HEX	前高后低，类型为1时卡号，4或7时为人员pid
		String pIdOrCardNo = tcpServiceRopo.getCommandParam().substring(2, 10);
//		Integer pIdOrCardNoInt = NumConvertUtil.HexStringToInt(pIdOrCardNo);
		Integer pIdOrCardNoInt = 0;
		if(payTypeInt == 4 || payTypeInt ==7){
			pIdOrCardNoInt = NumConvertUtil.HexStringToInt(pIdOrCardNo);
		}
		if(payTypeInt==1){
			Result result2 = payHandleFeignService.getCardInfo(companyId,pIdOrCardNo);
			if(result2.getCode() == 200){
				EntityCardInfo entityCardInfo = JSON.parseObject(JSON.toJSONString(result2.getData()),EntityCardInfo.class);
				pIdOrCardNoInt = entityCardInfo.getPId().intValue();
			}else{
				pIdOrCardNoInt = 0;
			}
		}

		if (payTypeInt == 0 && pIdOrCardNoInt == 0) {
			return null;
		}

		//操作类型	1	HEX	0x01金额消费；0x02计次消费；0x03金额充值；0x04次数充值；0x05订餐，0x06菜单消费；其他预留
		String handleType = tcpServiceRopo.getCommandParam().substring(12, 12);
		//消费类型	1	HEX	1-食堂；2-小卖部
		String comsumeType = tcpServiceRopo.getCommandParam().substring(12, 14);
		//记录号	4	HEX	前高后低
		String recode = tcpServiceRopo.getCommandParam().substring(14, 22);
		//交易时间	6	Bcd	Ymdhms
		String createtime = tcpServiceRopo.getCommandParam().substring(22, 34);

		//2022-10-27 09:06:35
		String dateStr = "20" + createtime.substring(0, 2)
				+ "-" + createtime.substring(2, 4)
				+ "-" + createtime.substring(4, 6)
				+ " " + createtime.substring(6, 8)
				+ ":" + createtime.substring(8, 10)
				+ ":" + createtime.substring(10);

		//消费金额/次数	4	HEX	前高后低（操作类型为0x02时为预扣款金额，可为0）
		Integer moneyInt = -1;
		String money = tcpServiceRopo.getCommandParam().substring(34, 42);
		if (!money.startsWith("ff")) {
			moneyInt = NumConvertUtil.HexStringToInt(money);
		}
		//设备交易号	13	HEX	设备交易号，4字节位设备号+ 7字节交易时间yyyyMMddHHmmssxxxx+2字节随机数
		String orderNo = tcpServiceRopo.getCommandParam().substring(42, 68);
		//在线/离线标识	1	HEX	0在线，1离线，2在线转离线
		String leave = tcpServiceRopo.getCommandParam().substring(68, 70);
		Integer leaveInt = NumConvertUtil.HexStringToInt(leave);

		//卡号查pId
//		if (payTypeInt == 1) {
//			Result result1 = payHandleFeignService.getCardInfo(companyId, pIdOrCardNo);
//			if (result1.getCode() != 200) {
//				resp.setCommandParam("0006",4,result1.getMsg());
//				String rc = resp.getHexStr();
//				return HexUtil.decodeHex(rc);
//			}
//			EntityCardInfo entityCardInfo = JSON.parseObject(JSON.toJSONString(result1.getData()), EntityCardInfo.class);
//			if(entityCardInfo.getCardState()!=1){
//				resp.setCommandParam("0007",4,"卡状态异常");
//				String rc = resp.getHexStr();
//				return HexUtil.decodeHex(rc);
//			}
//		}
		if (payTypeInt == 7) {
			payTypeInt = 3;
		}

		TradeRecordRequest request = new TradeRecordRequest();
		request.setCompanyId(companyId);
		request.setMachNo(tcpServiceRopo.getMachId());
		request.setTradeTime(dateStr);
		request.setLineSymbol(leaveInt);
		request.setTradeNo(orderNo);
		request.setAmount(moneyInt);
		request.setType(payTypeInt);
		request.setUserId(pIdOrCardNoInt.longValue());

		Result result = payHandleFeignService.saveXfRecordD(request);
		log.info("上传结果 【{}】【{}】",tcpServiceRopo,result);

		if (result==null || result.getCode() != 200) {
			resp.setCommandParam(result.getCode().toString(),4,result.getMsg());
			String rc = resp.getHexStr();
			return HexUtil.decodeHex(rc);
		}
		recodeUploadVo.setRecodeNo(recode);

		resp.setCommandParam(recodeUploadVo.getHexStr());
		String rc = resp.getHexStr();
		return HexUtil.decodeHex(rc);
	}

	@Override
	public byte[] balanceQuery(TcpServiceRopo tcpServiceRopo) throws Exception {
		//要返回的对象
		TcpServiceRopo resp = new TcpServiceRopo();
		//赋返回值  全是16进制字符串
		resp.setMachId(tcpServiceRopo.getMachId());
		resp.setEdition(tcpServiceRopo.getEdition());
		resp.setType(tcpServiceRopo.getType());
		resp.setPackageNum(tcpServiceRopo.getPackageNum());
		resp.setCommandType(tcpServiceRopo.getCommandType());

		BalanceQueryVo balanceQueryVo = new BalanceQueryVo();

		Long companyId = ((Integer) redisUtil.hmGet("tcpXfMach:" + tcpServiceRopo.getMachId(), "companyId")).longValue();

		String cardNo = tcpServiceRopo.getCommandParam().substring(2, 10);

		Map<String, Object> balance = new HashMap<>();
		balance.put("companyID", companyId);
		balance.put("type", 1);
		balance.put("cardNum", cardNo);

		RespMachMessage respMachMessage = payHandleFeignService.getBalance(balance);
		if (!respMachMessage.getCode().equals("0000")) {
			resp.setCommandParam(respMachMessage.getCode(),4,respMachMessage.getMsg());
			String rc = resp.getHexStr();
			return HexUtil.decodeHex(rc);
		}


		JSONObject jsonObject = JSON.parseObject(JSON.toJSONString(respMachMessage.getData()));

		JSONObject jsonObject1 = JSON.parseObject(JSON.toJSONString(jsonObject.get("accountInf")));

		Integer money = jsonObject1.getInteger("money");
		Integer allowance = jsonObject1.getInteger("allowance");

		String name = NumConvertUtil.toGBK(jsonObject1.getString("name"));
		if (name.length() < 40) {
			int len = name.length();
			for (int i = len; i < 40; i++) {
				name = name + "0";
			}
		}
		if(name.length()>40){
			name=name.substring(0,40);
		}

		//tcp 刷卡
		balanceQueryVo.setType("01");
		balanceQueryVo.setName(name);
		balanceQueryVo.setCardType("01");
		//Yyyymmddhhmmss
		balanceQueryVo.setValid("20990102030405");
		if(allowance==null){
			allowance= 0 ;
		}
		if(money==null){
			money= 0 ;
		}
		money  += allowance;
		balanceQueryVo.setBalance(NumConvertUtil.IntToHexStringNum(money, 8));
		balanceQueryVo.setSubBalance("00000000");
//		balanceQueryVo.setSubBalance(NumConvertUtil.IntToHexStringNum(allowance, 8));

		log.info("Tcp_balanceQuery-返回【{}】 【{}】", tcpServiceRopo, balanceQueryVo);


		resp.setCommandParam(balanceQueryVo.getHexStr());
		String rc = resp.getHexStr();
		return HexUtil.decodeHex(rc);
	}


	@Override
	public byte[] orderQuery(TcpServiceRopo tcpServiceRopo) throws Exception {
		//要返回的对象
		TcpServiceRopo resp = new TcpServiceRopo();
		//赋返回值  全是16进制字符串
		resp.setMachId(tcpServiceRopo.getMachId());
		resp.setEdition(tcpServiceRopo.getEdition());
		resp.setType(tcpServiceRopo.getType());
		resp.setPackageNum(tcpServiceRopo.getPackageNum());
		resp.setCommandType(tcpServiceRopo.getCommandType());

		OrderQueryVo orderQueryVo = new OrderQueryVo();

		Long companyId = ((Integer) redisUtil.hmGet("tcpXfMach:" + tcpServiceRopo.getMachId(), "companyId")).longValue();

		String typeStr = tcpServiceRopo.getCommandParam().substring(0,2);
		Integer type = NumConvertUtil.HexStringToInt(typeStr);

		if(type == 1 || type == 7){
			QrCodeQueryRequest qrCodeQueryRequest = new QrCodeQueryRequest();
			qrCodeQueryRequest.setCompanyId(companyId);
			qrCodeQueryRequest.setMachNo(tcpServiceRopo.getMachId());
			qrCodeQueryRequest.setTradeNo(tcpServiceRopo.getCommandParam().substring(4, 30));

			/**
			 * 	map.put("discount", entiyEntiyXfRecordProcess.getDiscount());
			 *  map.put("payAmount", entiyEntiyXfRecordProcess.getRealMoney());
			 *  Map<String,Object> mapAccountInf=new HashMap<>();
			 *  mapAccountInf.put("name", entiyEntiyXfRecordProcess.getPName());
			 *  mapAccountInf.put("money", entiyEntiyXfRecordProcess.getChargeBalance());
			 *  mapAccountInf.put("allowance", entiyEntiyXfRecordProcess.getSubMoney());
			 *  mapAccountInf.put("cardtype", entiyEntiyXfRecordProcess.getSubBalance());
			 *  map.put("accountInf",mapAccountInf);
			 */

			Result result = payHandleFeignService.onlinePayQuery(qrCodeQueryRequest);
			if (result.getCode() != 200) {
				log.info("Tcp_orderQuery-返回【{}】 【{}】 【{}】",qrCodeQueryRequest.getTradeNo(), tcpServiceRopo, result);
//				return null;
				if(result.getCode()==1001){
					//2025年3月20日14:41:45  查询结果为空返回失败
					resp.setCommandParam("3030",4,result.getMsg());
				}else{
					//支付中
					resp.setCommandParam("0802",4,result.getMsg());
				}
				String rc = resp.getHexStr();
				return HexUtil.decodeHex(rc);
			}

			JSONObject jsonObject = JSON.parseObject(JSON.toJSONString(result.getData()));
			JSONObject jsonObject1 = JSON.parseObject(JSON.toJSONString(jsonObject.get("accountInf")));

			Integer discount = jsonObject.getInteger("discount");
			Integer payAmount = jsonObject.getInteger("payAmount");

			Integer money = jsonObject1.getInteger("money");
			Integer allowance = jsonObject1.getInteger("allowance");
			String name = jsonObject1.getString("name");

			orderQueryVo.setDiscount(NumConvertUtil.IntToHexStringNum(Math.abs(discount), 4));
			orderQueryVo.setRealMoney(NumConvertUtil.IntToHexStringNum(Math.abs(payAmount), 8));
			orderQueryVo.setType(typeStr);
			orderQueryVo.setName(NumConvertUtil.toGBK(name));
			orderQueryVo.setCardType("01");
			orderQueryVo.setCardValid("20990102030405");
			orderQueryVo.setBalance(NumConvertUtil.IntToHexStringNum(money, 8));
			orderQueryVo.setSubBalance(NumConvertUtil.IntToHexStringNum(allowance, 8));

			resp.setCommandParam(orderQueryVo.getHexStr());
			String rc = resp.getHexStr();
			return HexUtil.decodeHex(rc);
		}
		if(type == 5){
			QrCodeQueryRequest qrCodeQueryRequest = new QrCodeQueryRequest();
			qrCodeQueryRequest.setCompanyId(companyId);
			qrCodeQueryRequest.setMachNo(tcpServiceRopo.getMachId());
			qrCodeQueryRequest.setTradeNo(tcpServiceRopo.getCommandParam().substring(4, 30));

			Result result = payHandleFeignService.qrCodeQuery(qrCodeQueryRequest);
			if (result.getCode() != 200) {
				log.info("Tcp_orderQuery-返回【{}】【{}】【{}】",qrCodeQueryRequest.getTradeNo(), tcpServiceRopo, result);
//				return null;
				//订单不存在
				if(result.getCode()==805){
					//2025年3月20日14:41:45  查询结果为空返回失败
					resp.setCommandParam("3030",4,result.getMsg());
				}else if(result.getCode()==3030){
					resp.setCommandParam("3030",4,result.getMsg());
				}else{
					//支付中
					resp.setCommandParam("0802",4,result.getMsg());
				}
				String rc = resp.getHexStr();
				return HexUtil.decodeHex(rc);
			}

			JSONObject jsonObject = JSON.parseObject(JSON.toJSONString(result.getData()));

			Integer discount = Math.abs(jsonObject.getInteger("discount"));
			Integer payAmount = Math.abs(jsonObject.getInteger("payAmount"));

			Integer money = 0;
			Integer allowance = 0;
			String name = "";
			if (name.length() < 20) {
				int len = name.length();
				for (int i = len; i < 20; i++) {
					name = name + "0";
				}
			}

			orderQueryVo.setDiscount(NumConvertUtil.IntToHexStringNum(discount, 4));
			orderQueryVo.setRealMoney(NumConvertUtil.IntToHexStringNum(payAmount, 8));
			orderQueryVo.setType(typeStr);
			orderQueryVo.setName(name);
			orderQueryVo.setCardType("01");
			orderQueryVo.setCardValid("20990102030405");
			orderQueryVo.setBalance(NumConvertUtil.IntToHexStringNum(money, 8));
			orderQueryVo.setSubBalance(NumConvertUtil.IntToHexStringNum(allowance, 8));

			log.info("Tcp_orderQuery-返回【{}】【{}】  【{}】",qrCodeQueryRequest.getTradeNo(), tcpServiceRopo, orderQueryVo);

			resp.setCommandParam(orderQueryVo.getHexStr());
			String rc = resp.getHexStr();
			return HexUtil.decodeHex(rc);
		}

		resp.setCommandParam("5000",4,"系统异常，联系管理员");
		String rc = resp.getHexStr();
		return HexUtil.decodeHex(rc);
	}

	@Override
	public byte[] payCount(TcpServiceRopo tcpServiceRopo) throws Exception {
		//要返回的对象
		TcpServiceRopo resp = new TcpServiceRopo();
		//赋返回值  全是16进制字符串
		resp.setMachId(tcpServiceRopo.getMachId());
		resp.setEdition(tcpServiceRopo.getEdition());
		resp.setType(tcpServiceRopo.getType());
		resp.setPackageNum(tcpServiceRopo.getPackageNum());
		resp.setCommandType(tcpServiceRopo.getCommandType());

		//参数查询类型	1	HEX	0x01 金额消费汇总
		//0x02 消费明细
		//其它保留
		String type = tcpServiceRopo.getCommandParam().substring(0, 2);
		Integer typeInt = NumConvertUtil.HexStringToInt(type);
		//查询方向	1	HEX	0x00 当前最新一笔
		//0x01 前一笔
		//0x02 后一笔
		String direct = tcpServiceRopo.getCommandParam().substring(2, 4);
		Integer directInt = NumConvertUtil.HexStringToInt(direct);
		//查询的年	1	HEX	例如：2014取14，以此类推
		String yyyy = "20" + NumConvertUtil.HexStringToInt(tcpServiceRopo.getCommandParam().substring(4, 6)).toString();
		//查询的月	1	HEX	自然月
		String mm = NumConvertUtil.HexStringToInt(tcpServiceRopo.getCommandParam().substring(6, 8)).toString();
		//查询的日	1	HEX	自然日
		String dd = NumConvertUtil.HexStringToInt(tcpServiceRopo.getCommandParam().substring(8, 10)).toString();
		//记录id	4
		String recode = tcpServiceRopo.getCommandParam().substring(10, 18);
		//当前笔数	2		首次为0，之后为返回值
		String current = tcpServiceRopo.getCommandParam().substring(18, 22);
		Integer currentInt = NumConvertUtil.HexStringToInt(current);


		Integer page = 1;
		if(currentInt < 2){
			 if(currentInt == 1 && directInt ==2 ){
				 page=2;
			 }else{
				 page=1;
			 }
		}else{
			if(directInt == 0){
				page = currentInt;
			}
			if(directInt == 1){
				currentInt--;
				page = currentInt;
			}
			if(directInt == 2){
				currentInt++;
				page = currentInt;
			}
		}

		Long companyId = ((Integer) redisUtil.hmGet("tcpXfMach:" + tcpServiceRopo.getMachId(), "companyId")).longValue();

		if(mm.length()==1){
			mm= "0"+mm;
		}
		if(dd.length()==1){
			dd= "0"+dd;
		}

		//"2022-10-13 01:08:22",
		String startTime = yyyy+ "-" + mm +"-" +dd +" " + "00:00:00";
		String endTime =yyyy+ "-" + mm +"-" +dd +" " + "23:59:59";

		if (typeInt == 1) {
			PayCountQueryVo payCountQueryVo = new PayCountQueryVo();

			/**
			 * {
			 *     "comId" : 1,
			 *     "deviceNo" : "21105463",
			 *     "startTime" : "2022-10-13 01:08:22",
			 *     "endTime" : "2022-10-13 23:08:22",
			 *     "page" : 1,
			 *     "size" : 1 ,
			 *     "mealNameInfos" : [],
			 *     "reportType" : 1
			 * }
			 */
			JSONObject jsonObject =new JSONObject();
			jsonObject.put("comId",companyId);
			jsonObject.put("deviceNo",tcpServiceRopo.getMachId());
			jsonObject.put("startTime",startTime);
			jsonObject.put("endTime",endTime);
			jsonObject.put("page",page);
			jsonObject.put("size",1);
			jsonObject.put("mealNameInfos",new ArrayList<>());
			jsonObject.put("reportType",1);
			Result result = xfRecodeClientService.getConsumeReports(jsonObject);

			if(result.getCode()!=200){
				resp.setCommandParam(String.valueOf(result.getCode()),4,result.getMsg());
				String rc = resp.getHexStr();
				return HexUtil.decodeHex(rc);
			}

			JSONObject jsonObject1 = JSON.parseObject(JSON.toJSONString(result.getData()));

			try {
				Object ob1 = jsonObject1.get("list");
				JSONArray array = (JSONArray)ob1;
				JSONObject jsonObject3 = (JSONObject)array.get(0);

				Integer allAmount = jsonObject3.getInteger("allAmount");
				Integer allTimes = jsonObject3.getInteger("allTimes");

				allAmount=Math.abs(allAmount);
				allTimes=Math.abs(allTimes);

				payCountQueryVo.setCountPayMoney(NumConvertUtil.IntToHexStringNum(allAmount,8));
				payCountQueryVo.setCountPayTimes(NumConvertUtil.IntToHexStringNum(allTimes,8));

			}catch (Exception e){
				log.info("汇总解析list 【{}】",e);
			}

			log.info("Tcp_payCount-返回【{}】 【{}】", tcpServiceRopo, payCountQueryVo);


			resp.setCommandParam(payCountQueryVo.getHexStr());
			String rc = resp.getHexStr();
			return HexUtil.decodeHex(rc);
		}


		if (typeInt == 2) {
			PayDetailQueryVo payDetailQueryVo = new PayDetailQueryVo();

			/**
			 * {
			 *     "comId" : 1,
			 *     "deviceNo" : "21105463",
			 *     "startTime" : "2022-10-13 01:08:22",
			 *     "endTime" : "2022-10-13 23:08:22",
			 *     "page" : 1,
			 *     "size" : 1
			 * }
			 */
			JSONObject jsonObject =new JSONObject();
			jsonObject.put("comId",companyId);
			jsonObject.put("deviceNo",tcpServiceRopo.getMachId());;
			jsonObject.put("startTime",startTime);
			jsonObject.put("endTime",endTime);
			jsonObject.put("page",page);
			jsonObject.put("size",1);
			Result result = xfRecodeClientService.getConsumeDetail(jsonObject);

			if(result.getCode()!=200){
				resp.setCommandParam(String.valueOf(result.getCode()),4,result.getMsg());
				String rc = resp.getHexStr();
				return HexUtil.decodeHex(rc);
			}

			JSONObject jsonObject1 = JSON.parseObject(JSON.toJSONString(result.getData()));

			Integer total =  jsonObject1.getInteger("total");
			if(total==null) total= 0;


			try {
				Object ob1 = jsonObject1.get("list");
				JSONArray array = (JSONArray)ob1;
				JSONObject jsonObject3 = (JSONObject)array.get(0);

				/**
				 * {
				 * 	"code": 200,
				 * 	"msg": "成功",
				 * 	"data": {
				 * 		"total": 19,
				 * 		"list": [
				 *                        {
				 * 				"id": 41142,
				 * 				"comId": 1,
				 * 				"deviceNo": "21105463",
				 * 				"deviceName": "南院院内超市",
				 * 				"pointId": 69,
				 * 				"pointName": "南院院内超市",
				 * 				"merchId": 49,
				 * 				"merchName": "南院食堂",
				 * 				"deptId": 880,
				 * 				"deptName": "康复科",
				 * 				"subBalance": 0,
				 * 				"accountNo": "39P113356",
				 * 				"cardNo": "113356",
				 * 				"discount": 0,
				 * 				"discountWay": 0,
				 * 				"payState": 1,
				 * 				"consMoney": -7200,
				 * 				"realMoney": -7200,
				 * 				"subMoney": 0,
				 * 				"orderNo": "21105463202210130840417709",
				 * 				"platOrderNo": null,
				 * 				"channelOrderNo": null,
				 * 				"monthValue": "202210",
				 * 				"origOrderNo": null,
				 * 				"consTime": "2022-10-13 08:40:42",
				 * 				"payTime": "2022-10-13 08:40:42",
				 * 				"payAmount": 7200,
				 * 				"mealDate": "2022-10-13",
				 * 				"mealNo": "1",
				 * 				"payChannelNo": null,
				 * 				"consState": 1,
				 * 				"consType": 1,
				 * 				"opType": 22,
				 * 				"opTypeDiff": 100,
				 * 				"createTime": "2022-10-13 08:40:42",
				 * 				"ifRefund": 0,
				 * 				"refundTime": null,
				 * 				"face": "http://193.112.157.241:9002/yan/2022/10/13/0910b015204747c7aa195b23a976c878_戴婉君_113356_21105463202210130840417709_1665621641075.jpg",
				 * 				"adminName": "",
				 * 				"amountother": null,
				 * 				"timesother": null,
				 * 				"allAmount": null,
				 * 				"allTimes": null,
				 * 				"allRefund": null,
				 * 				"allRefundTimes": null,
				 * 				"sum": null,
				 * 				"charge": null,
				 * 				"subsidy": null,
				 * 				"mealName": null,
				 * 				"amountType": null,
				 * 				"amount": null,
				 * 				"orgOrderNo": null,
				 * 				"reportType": null,
				 * 				"isRefund": null,
				 * 				"balance": null,
				 * 				"account": null,
				 * 				"times": null,
				 * 				"orderNum": null,
				 * 				"refundNum": null,
				 * 				"refundAmount": null,
				 * 				"amount1": null,
				 * 				"times1": null,
				 * 				"amount2": null,
				 * 				"times2": null,
				 * 				"amount3": null,
				 * 				"times3": null,
				 * 				"amount4": null,
				 * 				"times4": null,
				 * 				"amount5": null,
				 * 				"times5": null,
				 * 				"amount6": null,
				 * 				"times6": null,
				 * 				"amount7": null,
				 * 				"times7": null,
				 * 				"amount8": null,
				 * 				"times8": null,
				 * 				"amount9": null,
				 * 				"times9": null,
				 * 				"amount10": null,
				 * 				"times10": null,
				 * 				"amount11": null,
				 * 				"times11": null,
				 * 				"amount12": null,
				 * 				"times12": null,
				 * 				"closeBalance": null,
				 * 				"openBalance": null,
				 * 				"consumeAmount": null,
				 * 				"consumeNumber": null,
				 * 				"rechargeAmount": null,
				 * 				"rechargeNumber": null,
				 * 				"settleAmount": null,
				 * 				"settleNumber": null,
				 * 				"consCancelAmount": null,
				 * 				"consCancelNumber": null,
				 * 				"date": null,
				 * 				"cashAmount": null,
				 * 				"cashNumber": null,
				 * 				"cashoutAmount": null,
				 * 				"cashoutNumber": null,
				 * 				"mngUserId": null,
				 * 				"consNumber": null,
				 * 				"chargeAmount": null,
				 * 				"subAmount": null,
				 * 				"consAmount": null,
				 * 				"stime": null,
				 * 				"chargeBalance": 32400,
				 * 				"pId": 113356,
				 * 				"pCode": "15579383927",
				 * 				"pName": "戴婉君",
				 * 				"chargeMoney": -7200,
				 * 				"adminId": 0,
				 * 				"pPhotoUrl2": null
				 *            }
				 * 		]
				 * 	}
				 * }
				 */

				Integer realMoney = jsonObject3.getInteger("realMoney");
				Integer opType = jsonObject3.getInteger("opType");
				String orderNo = jsonObject3.getString("orderNo");
				String createTime = jsonObject3.getString("payTime");


				payDetailQueryVo.setMoney(NumConvertUtil.IntToHexStringNum(Math.abs(realMoney),8));
				payDetailQueryVo.setPayType(NumConvertUtil.IntToHexStringNum(opType,2));
				payDetailQueryVo.setCurrent(NumConvertUtil.IntToHexStringNum(page ,4));
				payDetailQueryVo.setOrderNo(orderNo);
				payDetailQueryVo.setPayTime(DateUtils.getStrDate(DateUtils.strToDate(createTime),"yyMMddHHmmss"));

			}catch (Exception e){
				log.info("汇总明细list 【{}】",e);
			}
			payDetailQueryVo.setTotal(NumConvertUtil.IntToHexStringNum(total,4));

			resp.setCommandParam(payDetailQueryVo.getHexStr());
			String rc = resp.getHexStr();
			return HexUtil.decodeHex(rc);
		}

		resp.setCommandParam("5000",4,"类型不支持");
		String rc = resp.getHexStr();
		return HexUtil.decodeHex(rc);
	}

//	public static void main(String[] args) throws Exception{
//		byte[] gbkText = {(byte) 0x0a,(byte) 0xbf,(byte) 0xa8
//				,(byte) 0xd7
//				,(byte) 0xb4
//				,(byte) 0xcc
//				,(byte) 0xac
//				,(byte) 0xd2
//				,(byte) 0xec
//				,(byte) 0xb3
//				,(byte) 0xa3};
//		String testStr = new String(gbkText,"GBK");
//		System.out.println(testStr);
//	//0abfa8
//	}
//

	public static void main(String[] args) {
		String str1 = "ffffffff";
		String str2 = "fff";
		String str3 = "f";
		String str4 = "fffFFF";

		System.out.println(isAllF(str1)); // true
		System.out.println(isAllF(str2)); // true
		System.out.println(isAllF(str3)); // true
		System.out.println(isAllF(str4)); // false
	}


	public static boolean isAllF(String str) {
		return str.replaceAll("[^f]", "").equals(str);
	}
}
